/*
 * OpenThe9Box (OT9B): Java(TM) API for NeufBox REST interface.
 * Copyright (C) 2015 ScalAgent D.T.
 * Copyright (C) 2015 Turbotel
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA.
 *
 * Initial developer(s): Freyssinet Andre (ScalAgent D.T.)
 * Contributor(s): 
 */
package org.turbotel.ot9b.tools;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

/**
 * This class allows the encryption of login and password.
 */
public class Hash {
  /**
   * Convert byte array to String.
   * 
   * @param bytes
   * @return
   */
  public static String bytesToString(byte[] bytes) {
    StringBuffer hash = new StringBuffer();
    for (int i = 0; i < bytes.length; i++)
    {
          String hex = Integer.toHexString(0xFF & bytes[i]);
          if (hex.length() == 1)
            hash.append('0');
          
          hash.append(hex);
    }
    return hash.toString();
  }
  
  /**
   * Hash SHA 256.
   * 
   * @param data
   * @return
   * @throws NoSuchAlgorithmException
   * @throws UnsupportedEncodingException
   */
  public static String hashSHA256(String data) throws NoSuchAlgorithmException, UnsupportedEncodingException {
    MessageDigest md = MessageDigest.getInstance("SHA-256");
    md.update(data.getBytes("UTF-8"));
    byte[] bytes = md.digest();
    
    return bytesToString(bytes);
  }
  
  /**
   * Hash Hmac SHA 256.
   * 
   * @param key
   * @param data
   * @return
   * @throws UnsupportedEncodingException
   * @throws NoSuchAlgorithmException
   * @throws InvalidKeyException
   */
  public static String hashHmacSHA256(String key, String data) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
    SecretKeySpec secretKey = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
    Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(secretKey);
    byte[] bytes = mac.doFinal(data.getBytes("UTF-8")); 
      
    return bytesToString(bytes);
  }
}
